import React from 'react';
import { Form, Input, Button, Switch, TreeSelect, Space, message } from 'antd';
import { SafetyCertificateOutlined } from '@ant-design/icons';
import { rolePermissionStore } from '../store/rolePermission';
import { roleUserStore } from '../store/roleUserStore';
import { RolePermission } from '../store/types';

interface RolePermissionFormProps {
  type: 'create' | 'edit' | 'view';
  initialValues?: any;
  onCancel: () => void;
}

const RolePermissionForm: React.FC<RolePermissionFormProps> = ({ type, initialValues, onCancel }) => {
  const [form] = Form.useForm();

  const onFinish = (values: RolePermission) => {
    rolePermissionStore.saveRolePermission(values);
    message.success(type === 'create' ? '创建成功' : '更新成功');
    onCancel();
  };

  const getSelectedKeys = (treeData: any[]): string[] => {
    const keys: string[] = [];
    const traverse = (nodes: any[]) => {
      nodes.forEach(node => {
        keys.push(node.value);
        if (node.children) {
          traverse(node.children);
        }
      });
    };
    traverse(treeData);
    return keys;
  };

  const isViewMode = type === 'view';
  const isEditMode = type === 'edit';
  if(isViewMode || isEditMode){
    initialValues.roles = [initialValues?.roleId ];
    initialValues.permissions=[initialValues?.permissionId];
  }
  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      initialValues={{
        ...initialValues,
        status: initialValues?.status === 'active',
      }}
      disabled={isViewMode}
    >
      <Form.Item
        label="角色"
        name={'roles'}
        rules={[{ required: true, message: '请选择角色' }]}
      >
        <TreeSelect
          treeData={roleUserStore.roleOptions}
          placeholder="请选择角色"
          treeCheckable={!isEditMode}
          showCheckedStrategy="SHOW_PARENT"
          style={{ width: '100%' }}
          // defaultValue={getSelectedKeys(roleOptions)}
        />
      </Form.Item>

      <Form.Item
        label="权限项"
        name={'permissions'}
        rules={[{ required: true, message: '请选择权限项' }]}
      >
        <TreeSelect
          treeData={rolePermissionStore.permissionOptions}
          placeholder="请选择权限项"
          treeCheckable={!isEditMode}
          showCheckedStrategy="SHOW_PARENT"
          style={{ width: '100%' }}
          // defaultValue={getSelectedKeys(menuTreeData)}
        />
      </Form.Item>

      {!isViewMode && (
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              {type === 'create' ? '创建' : '保存'}
            </Button>
            <Button onClick={onCancel}>取消</Button>
          </Space>
        </Form.Item>
      )}
    </Form>
  );
};

export default RolePermissionForm; 